import { FC, useContext, useState } from 'react';
import styles from './index.less';
import { getDashed, loopTreeNode } from '../../utils';
import { DesignRedux } from '../../DesignRedux';
import TextBox from './TextBox';
import ImgBox from './ImgBox';

const TitleFC: FC<any> = (props: any) => {
  const { property } = props;
  const { leftImg, centerText, rightImg } = property.comProperty;
  const [editNodeHtml, setEditNodeHtml] = useState('');

  // 在使用useContext解构出color中想要传递的值，就是最终返回给我们的值
  const { globalState, dispatch } = useContext(DesignRedux);
  const { currentNode, schema } = globalState; // 右侧元素属性

  const onClickNode = (event, cNode) => {
    event.preventDefault;
    event.stopPropagation;
    //否则，我们需要使用IE的方式来取消事件冒泡
    dispatch({ currentNode: cNode }); // 当前节点开始编辑
  };

  // 双击
  const onDoubleClickNode = (event, cNode) => {
    event.preventDefault;
    event.stopPropagation;
  };

  const onChangeText = (event) => {
    setEditNodeHtml(event.target.innerHTML);
  };

  const onBlur = (event) => {
    if (currentNode.id && editNodeHtml) {
      let newSchema = [...schema];
      loopTreeNode(newSchema, property.key, (item) => {
        item.comProperty.centerText.title = editNodeHtml;
      });

      dispatch({
        schema: newSchema,
        currentNode: {}, // 获取当前
      });
      setEditNodeHtml('');
    }
  };

  return (
    <div className={styles.ztTitle}>
      {/*左侧图片*/}
      <ImgBox centerText={leftImg}>
        <div
          className={getDashed(currentNode, leftImg)}
          onClick={(event) => onClickNode(event, leftImg)}
        >
          <img src={leftImg.src} alt="" />
        </div>
      </ImgBox>

      {/*标题*/}
      <TextBox content={centerText} parentNode={property}>
        <div
          className={getDashed(currentNode, centerText)}
          contentEditable={true}
          onClick={(event) => onClickNode(event, centerText)}
          onBlur={onBlur}
          onInput={onChangeText}
          onDoubleClick={(event) => onDoubleClickNode(event, centerText)}
          dangerouslySetInnerHTML={{ __html: centerText.title }}
        />
      </TextBox>

      {/*右侧图片*/}
      <ImgBox centerText={rightImg}>
        <div
          className={getDashed(currentNode, rightImg)}
          onClick={(event) => onClickNode(event, rightImg)}
        >
          <img src={rightImg.src} alt="" />
        </div>
      </ImgBox>
    </div>
  );
};

export default TitleFC;
